const fse = require('fs-extra')
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const ejs = require('ejs')

const { SupportedEditor, SupportedLanguage, SupportedStyleSheets, SupportedFramework } = require('./consts')

const applyVSCodeSettings = ({ language, framework, styleSheets, includeHtml }) => {
	// 生成 settings.json 文件
	const settingPath = path.resolve(__dirname, '../template/.vscode/settings.json')
	const settingData = ejs.render(fs.readFileSync(settingPath, 'utf-8'), {
		supportedLanguage: SupportedLanguage,
		language,
		styleSheets,
		supportedStyleSheets: SupportedStyleSheets,
		framework,
		supportedFramework: SupportedFramework,
		html: includeHtml
	})

	const settingFile = path.resolve(process.cwd(), './.vscode/settings.json')
	fse.ensureFileSync(settingFile)
	fs.writeFileSync(settingFile, settingData, 'utf-8')

	// 生成 extensions.json 文件
	const extensionPath = path.resolve(__dirname, '../template/.vscode/extensions.json')
	const extensionData = ejs.render(fs.readFileSync(extensionPath, 'utf-8'), {
		style: styleSheets !== SupportedStyleSheets.others,
		vue: framework === SupportedFramework.vue2 || framework === SupportedFramework.vue3
	})

	const extensionFile = path.resolve(process.cwd(), './.vscode/extensions.json')
	fse.ensureFileSync(extensionFile)
	fs.writeFileSync(extensionFile, extensionData, 'utf-8')
}

module.exports = {
	apply: options => {
		console.log(chalk.blue('生成编辑器设置...'))
		const { editorType } = options

		// 没有选择使用何种编辑器
		if (editorType === SupportedEditor.others) {
			return
		}

		// 应用 VSCode 编辑器设置
		if (editorType === SupportedEditor.VSCode) {
			applyVSCodeSettings(options)
		}
	}
}
